//
//  PageContentView.swift
//  WhyTest
//
//  Created by 宋广越 on 2022/2/14.
//

import UIKit
protocol PageContentViewDelegate : AnyObject{
    func pageContentViewDelegate(pageContentView : PageContentView,progress :CGFloat,sourceIndex : Int,targetIndex : Int)
}
private let ContentCellID = "ContentCellID"
class PageContentView: UIView {
    //定义属性
    private var childVcs : [UIViewController]
    //定义代理局部bianliang
    weak var delegate : PageContentViewDelegate?
    private weak var parentViewController : UIViewController?
    private var startOffsetX : CGFloat = 0
    private var isForbidScrollDelegate = false
    private  lazy  var  collectionView : UICollectionView = { [weak self] in
       //create layout
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)!
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        let collectionView = UICollectionView(frame: CGRectZero,collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isPagingEnabled = true
        collectionView.bounces = false
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.scrollsToTop = false
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
        
        return collectionView
     }()
    //自定义构造函数
    init(frame: CGRect,childVcs : [UIViewController],parentViewController : UIViewController?){
        self.childVcs = childVcs
        self.parentViewController = parentViewController
        super.init(frame: frame)
        //设置UI
        setupUI()
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
   
    }
  //设置ui
    extension PageContentView {

        private func setupUI(){
            //set all the controllers add to parent
            for childVc in childVcs {
                parentViewController?.addChild(childVc)
            }
            //add uicollectionView，use in cell put the controller View
            addSubview(collectionView)
            collectionView.frame = bounds
        
        }
}

extension PageContentView : UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVcs.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //create cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
        // set cell content
        //重复利用cell
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        let childVc =  childVcs[indexPath.item]
        childVc.view.frame = cell.contentView.bounds
        cell.contentView.addSubview(childVc.view)
        return cell
    }
      
}
//遵守uicollectionViewDelegate 代理协议
extension PageContentView : UICollectionViewDelegate {
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        isForbidScrollDelegate = false
        startOffsetX = scrollView.contentOffset.x
    }
    
    
    
    //我要通过你的代理方法获取你的属性值呀
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if isForbidScrollDelegate { return }
          // 获取我们需要的数据
        var progress : CGFloat = 0
        var sourceIndex : Int = 0
        var targetIndex : Int = 0
        let scrollViewW = scrollView.frame.width
         //判断是左滑还是又滑
        let currentOffsetX = scrollView.contentOffset.x
        if currentOffsetX > startOffsetX { //左滑
            progress = currentOffsetX/scrollViewW - floor(currentOffsetX/scrollViewW)
            //计算当前的sourceIndex
            sourceIndex = Int(currentOffsetX / scrollViewW)
            //计算targetIndex
            targetIndex = sourceIndex + 1
            if(targetIndex >= childVcs.count){
                targetIndex = childVcs.count - 1
            }
            //如果完全划过去
            if currentOffsetX - startOffsetX == scrollViewW {
                progress = 1
                targetIndex = sourceIndex
            }
                
        }else {//右滑
            progress = floor(currentOffsetX/scrollViewW)+1 - currentOffsetX/scrollViewW
            //计算targetIndex
            targetIndex = Int(currentOffsetX / scrollViewW)
            //计算sourceIndex
            sourceIndex = targetIndex + 1
            
            if(sourceIndex >= childVcs.count){
                sourceIndex = childVcs.count - 1
            }
//            //如果完全划过去
//            if startOffsetX - currentOffsetX == scrollViewW {
//                progress = 1
//                targetIndex = sourceIndex
//            }
        }
        //将progress/sourceIndex/targetIndex 传递给titleView
        delegate?.pageContentViewDelegate(pageContentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
        
    }
    
}

//对外暴露的方法
extension PageContentView {
    func setCurrentIndex(currentIndex :Int ) {
        isForbidScrollDelegate = true
        //
        let offsetX = CGFloat(currentIndex) * collectionView.frame.width
        collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
       
    }
}


